import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/contract_controller.dart';
import '../controller/auth_controller.dart';
import '../controller/payment_controller.dart';
import '../controller/tapjoy_controller.dart';
import '../controller/setting_controller.dart';
import '../model/contract_list_model.dart';
import 'web_view_page.dart';

class MiningPlansBottomSheet extends StatefulWidget {
  final ContractListResponse? contractData;
  final VoidCallback? onFreePlanTap;
  final VoidCallback? onOfferWallPlanTap;
  final VoidCallback? onRunningPlansTap;
  final Function(PaidContract)? onPurchaseTap;
  // 外部传入：Free Plan 卡片的图标、标题、描述
  final String? freePlanIconAsset;
  final String? freePlanTitle;
  final String? freePlanDescription;
  // 外部传入：Offerwall 卡片的图标、标题、描述
  final String? offerWallIconAsset;
  final String? offerWallTitle;
  final String? offerWallDescription;

  const MiningPlansBottomSheet({
    Key? key,
    this.contractData,
    this.onFreePlanTap,
    this.onOfferWallPlanTap,
    this.onRunningPlansTap,
    this.onPurchaseTap,
    this.freePlanIconAsset,
    this.freePlanTitle,
    this.freePlanDescription,
    this.offerWallIconAsset,
    this.offerWallTitle,
    this.offerWallDescription,
  }) : super(key: key);

  @override
  State<MiningPlansBottomSheet> createState() => _MiningPlansBottomSheetState();
}

class _MiningPlansBottomSheetState extends State<MiningPlansBottomSheet> {
  late final ContractController contractController;
  late final PaymentController paymentController;
  final Map<int, bool> _loadingStates = {};
  final Map<int, DateTime> _lastClickTimes = {}; // 记录每个合约的最后点击时间
  static const int _debounceDelayMs = 1000; // 防抖延迟时间（毫秒）

  @override
  void initState() {
    super.initState();
    // 确保依赖已注册，避免在构造时找不到
    if (!Get.isRegistered<PaymentController>()) {
      Get.put(PaymentController());
    }
    if (!Get.isRegistered<ContractController>()) {
      Get.put(ContractController());
    }
    contractController = Get.find<ContractController>();
    paymentController = Get.find<PaymentController>();
  }

  // 默认任务墙点击行为：通过 TapjoyController 展示
  Future<void> _onOfferWallTap() async {
    try {
      final tapjoy = Get.isRegistered<TapjoyController>()
          ? Get.find<TapjoyController>()
          : Get.put(TapjoyController());
      // 若尚未连接，尝试按平台连接一次，提升首次点击成功率
      if (!tapjoy.isConnected.value) {
        final String sdkKey = Platform.isAndroid
            ? '3ezcC4_TSSGTa712qMVDqwECxteDCeLa4OJx8vywEIzr4d6LtZlAKB-nLfsH'
            : 'jsh3Nk1ISqOmRGcsGq699gEB6LFTnjhQLwDLuvqrwEg1bR_MLyf14EmkJLze';
        String? userId;
        if (Get.isRegistered<AuthController>()) {
          final auth = Get.find<AuthController>();
          userId = auth.currentUser.value?.uid.toString();
        }
        final ok = await tapjoy.connect(sdkKey: sdkKey, userId: userId);
        if (!ok) {
          debugPrint('Tapjoy connect failed on offerwall tap');
          return;
        }
      }
      await tapjoy.showOfferwall();
    } catch (e) {
      // 可选：提示或日志
      debugPrint('Offerwall show error: $e');
    }
  }

  // 处理购买逻辑，参考ContractCard的_handlePurchase方法
  Future<void> _handlePurchase(PaidContract contract) async {
    final now = DateTime.now();
    final lastClickTime = _lastClickTimes[contract.id];

    // 防抖检查：如果距离上次点击时间小于防抖延迟，则忽略此次点击
    if (lastClickTime != null &&
        now.difference(lastClickTime).inMilliseconds < _debounceDelayMs) {
      return;
    }

    // 防止重复点击
    if (_loadingStates[contract.id] == true) return;

    // 更新最后点击时间
    _lastClickTimes[contract.id] = now;

    setState(() {
      _loadingStates[contract.id] = true;
    });

    try {
      await contractController.subscribePaidContract(contract);

      // 调用原有的回调（如果需要）
      widget.onPurchaseTap?.call(contract);
    } catch (e) {
      // 支付失败提示
      // Get.snackbar(
      //   '支付失败',
      //   e.toString(),
      //   backgroundColor: Colors.red,
      //   colorText: Colors.white,
      //   duration: const Duration(seconds: 3),
      // );
    } finally {
      if (mounted) {
        setState(() {
          _loadingStates[contract.id] = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    // 使用屏幕高度的75%，增加弹窗高度
    final finalHeight = screenHeight * 0.75;

    return Container(
      height: finalHeight,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFF1A1A1A), // 深灰色
            Color(0xFF0D0D0D), // 更深的灰色
          ],
        ),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          // 拖拽手柄
          Container(
            margin: const EdgeInsets.only(top: 12),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[600],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 20),

          // 主要内容区域 - 使用Stack来叠加底部渐变
          Expanded(
            child: Stack(
              children: [
                // 可滚动内容
                SingleChildScrollView(
                  padding: const EdgeInsets.only(
                    left: 20,
                    right: 20,
                    bottom: 100, // 增加底部padding以避免与固定底部区域重合
                  ),
                  child: Column(
                    children: [
                      // Free Plan 和 Running Plans 卡片
                      Row(
                        children: [
                          Expanded(
                            child: _buildFreePlanCard(
                              iconAsset: widget.freePlanIconAsset ?? 'assets/free_plan_icon_pin.png',
                              title: widget.freePlanTitle ?? 'Free Plan',
                              description: widget.freePlanDescription ?? 'Watch Ads \nGet More Time',
                              btnTitle: "WATCH",
                              onTap: widget.onFreePlanTap,
                            ),
                          ),
                          const SizedBox(width: 12),
                          // Expanded(
                          //   child: _buildFreePlanCard(
                          //     iconAsset: widget.offerWallIconAsset ?? 'assets/task_plan_icon_pin.png',
                          //     title: widget.offerWallTitle ?? 'Task Plan',
                          //     description: widget.offerWallDescription ?? 'Do Tasks \nGet Plans',
                          //     btnTitle: "EARN",
                          //     onTap: widget.onOfferWallPlanTap ?? _onOfferWallTap,
                          //   ),
                          // ),
                          // const SizedBox(width: 12),
                          Expanded(
                            child: _buildRunningPlansCard(
                              onTap: widget.onRunningPlansTap,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 20),

                      // 挖矿计划列表
                      if (widget.contractData?.list != null)
                        ...widget.contractData!.list
                            .map((contract) => _buildPlanCard(contract))
                            .toList(),
                    ],
                  ),
                ),

                // 底部固定的法律条款链接 - 使用更强的渐变遮罩效果
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Container(
                    height: 100, // 增加高度以提供更好的渐变效果
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          const Color(0xFF0D0D0D).withOpacity(0.3),
                          const Color(0xFF0D0D0D).withOpacity(0.8),
                          const Color(0xFF0D0D0D),
                        ],
                        stops: const [0.0, 0.2, 0.6, 1.0],
                      ),
                    ),
                    child: Align(
                      alignment: Alignment.bottomCenter,
                      child: Container(
                        // 添加背景色确保文字可读性
                        decoration: BoxDecoration(
                          color: const Color(0xFF0D0D0D).withOpacity(0.95),
                          borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(12),
                            topRight: Radius.circular(12),
                          ),
                        ),
                        width: double.infinity,
                        padding: EdgeInsets.only(
                          left: 20,
                          right: 20,
                          top: 12,
                          bottom: MediaQuery.of(context).padding.bottom + 12,
                        ),
                        child: _buildBottomLinks(),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFreePlanCard({
    required String iconAsset,
    required String title,
    required String description,
    required String btnTitle,
    VoidCallback? onTap,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(color: const Color(0xFFFFD700), width: 1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          // 图片
          Image.asset(
            iconAsset,
            width: 48,
            height: 48,
          ),
          const SizedBox(height: 12),

          // 标题和副标题 - 居中
          Text(
            title,
            textAlign: TextAlign.center,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            description,
            textAlign: TextAlign.center,
            style: const TextStyle(
              color: Colors.grey,
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 16),

          // 黄色渐变边框按钮
          SizedBox(
            width: double.infinity,
            child: Container(
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Container(
                margin: const EdgeInsets.all(1.5),
                decoration: BoxDecoration(
                  color: const Color(0xFF1A1A1A),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    borderRadius: BorderRadius.circular(14),
                    onTap: onTap,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 10),
                      child: Center(
                        child: ShaderMask(
                          shaderCallback: (Rect bounds) {
                            return const LinearGradient(
                              colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                            ).createShader(bounds);
                          },
                          child:  Text(
                            btnTitle,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(height: 5),
        ],
      ),
    );
  }

  Widget _buildRunningPlansCard({VoidCallback? onTap}) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(color: const Color(0xFFFFD700), width: 1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          // 图片
          Image.asset(
            'assets/runing_plan_icon.png',
            width: 48,
            height: 48,
          ),
          const SizedBox(height: 12),

          // 标题和副标题 - 居中
          const Text(
            'My Plans',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          const Text(
            'View Active\nPlans',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.grey,
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 16),

          // 灰色描边按钮
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: onTap,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.transparent,
                foregroundColor: Colors.grey,
                side: const BorderSide(color: Colors.grey, width: 1),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                padding: const EdgeInsets.symmetric(vertical: 6),
              ),
              child: const Text(
                'VIEW',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTopCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required String buttonText,
    required Color buttonColor,
    Color? borderColor,
    VoidCallback? onTap,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(color: const Color(0xFFFFD700), width: 1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            icon,
            color: const Color(0xFFFFD700),
            size: 32,
          ),
          const SizedBox(height: 12),
          Text(
            title,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            subtitle,
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: onTap,
              style: ElevatedButton.styleFrom(
                backgroundColor: buttonColor,
                foregroundColor: buttonColor == Colors.transparent
                    ? const Color(0xFFFFD700)
                    : Colors.black,
                side: borderColor != null
                    ? BorderSide(color: borderColor, width: 1)
                    : null,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                padding: const EdgeInsets.symmetric(vertical: 6),
              ),
              child: Text(
                buttonText,
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlanCard(PaidContract contract) {
    // 根据计划名称选择对应图标
    String iconAsset;
    switch (contract.title.toLowerCase()) {
      case 'basic plan':
        iconAsset = 'assets/base_plan_icon.png';
        break;
      case 'pro plan':
        iconAsset = 'assets/pro_plan_icon.png';
        break;
      case 'elite plan':
        iconAsset = 'assets/advance_plan_icon.png';
        break;
      default:
        iconAsset = 'assets/advance_plan_icon.png'; // 默认图标
    }

    return GestureDetector(
      onTap: () => _handlePurchase(contract),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Container(
          margin: const EdgeInsets.all(2), // 渐变边框宽度
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: const Color(0xFF1A1A1A), // 深色背景
            borderRadius: BorderRadius.circular(10),
          ),
          child: Row(
            children: [
              // 图标
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  border: Border.all(color: const Color(0xFFFFD700), width: 1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.asset(
                    iconAsset,
                    width: 48,
                    height: 48,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              const SizedBox(width: 16),

              // 计划信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      contract.title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    ShaderMask(
                      shaderCallback: (Rect bounds) {
                        return const LinearGradient(
                          colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ).createShader(bounds);
                      },
                      child: Text(
                        contract.computingPower,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 购买按钮和价格 - 与算力文本垂直居中对齐
              Align(
                alignment: Alignment.center,
                child: Column(mainAxisSize: MainAxisSize.min, children: [
                  // 价格文本 - 黄色渐变
                  ShaderMask(
                    shaderCallback: (Rect bounds) {
                      return const LinearGradient(
                        colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ).createShader(bounds);
                    },
                    child: Text(
                      paymentController.formatPrice(Platform.isAndroid
                          ? contract.googleGoods
                          : contract.appleGoods),
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ),
                  const SizedBox(height: 6),
                  // 购买按钮
                  ElevatedButton(
                    onPressed: _loadingStates[contract.id] == true
                        ? null
                        : () => _handlePurchase(contract),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.transparent,
                      foregroundColor: const Color(0xFFFFD700),
                      shadowColor: Colors.transparent,
                      side:
                          const BorderSide(color: Color(0xFFFFD700), width: 1),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 8),
                    ),
                    child: _loadingStates[contract.id] == true
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                  Color(0xFFFFD700)),
                            ),
                          )
                        : const Text(
                            'PURCHASE',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                  ),
                ]),
              )
            ],
          ),
        ),
      ),
    );
  }

  // 构建底部法律条款和恢复购买链接
  Widget _buildBottomLinks() {
    if (Platform.isAndroid) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 第一行：EULA | Terms of Use | Privacy Policy
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // _buildLinkText('EULA', () => _openLink('eula')),
              // _buildSeparator(),
              _buildLinkText('Terms of Use', () => _openLink('terms')),
              _buildSeparator(),
              _buildLinkText('Privacy Policy', () => _openLink('privacy')),
            ],
          ),
          // const SizedBox(height: 8),
          // // 第二行：Restore Purchase
          // _buildLinkText('Restore Purchase', () => _handleRestorePurchase()),
        ],
      );
    } else {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 第一行：EULA | Terms of Use | Privacy Policy
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildLinkText('EULA', () => _openLink('eula')),
              _buildSeparator(),
              _buildLinkText('Terms of Use', () => _openLink('terms')),
              _buildSeparator(),
              _buildLinkText('Privacy Policy', () => _openLink('privacy')),
            ],
          ),
          const SizedBox(height: 8),
          // 第二行：Restore Purchase
          _buildLinkText('Restore Purchase', () => _handleRestorePurchase()),
        ],
      );
    }
  }

  // 构建链接文本
  Widget _buildLinkText(String text, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Text(
        text,
        style: TextStyle(
          color: Colors.grey[400],
          fontSize: 11,
          fontWeight: FontWeight.w400,
        ),
      ),
    );
  }

  // 构建分隔符
  Widget _buildSeparator() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 6),
      child: Text(
        '|',
        style: TextStyle(
          color: Colors.grey[500],
          fontSize: 11,
        ),
      ),
    );
  }

  // 处理链接点击
  void _openLink(String type) {
    // 尝试获取 SettingController 实例
    SettingController? settingController;
    try {
      settingController = Get.find<SettingController>();
    } catch (e) {
      // 如果找不到实例，settingController 将保持为 null
    }

    String finalUrl;
    String title;

    // 根据URL类型设置不同的标题和URL
    switch (type) {
      case 'eula':
        title = 'EULA';
        finalUrl =
            'https://www.apple.com/legal/internet-services/itunes/dev/stdeula';
        break;
      case 'terms':
        title = 'Terms of Use';
        finalUrl = settingController != null &&
                settingController.userAgreementUrl.value.isNotEmpty
            ? settingController.userAgreementUrl.value
            : 'https://bit-fury.com';
        break;
      case 'privacy':
        title = 'Privacy Policy';
        finalUrl = settingController != null &&
                settingController.privacyPolicyUrl.value.isNotEmpty
            ? settingController.privacyPolicyUrl.value
            : 'https://bit-fury.com';
        break;
      default:
        return;
    }

    Get.to(() => WebViewPage(
          url: finalUrl,
          title: title,
        ));
  }

  // 处理恢复购买
  void _handleRestorePurchase() {
    // 调用支付控制器的恢复购买方法
    paymentController.restorePurchases();
  }

  // 静态方法用于显示底部弹窗
  static void show(
    BuildContext context, {
    ContractListResponse? contractData,
    required VoidCallback onFreePlanTap,
    VoidCallback? onOfferWallPlanTap,
    required VoidCallback onRunningPlansTap,
    required Function(PaidContract) onPurchaseTap,
  }) {
    // 确保 ContractController 和 PaymentController 已注册
    if (!Get.isRegistered<ContractController>()) {
      Get.put(ContractController());
    }
    if (!Get.isRegistered<PaymentController>()) {
      Get.put(PaymentController());
    }

    final screenHeight = MediaQuery.of(context).size.height;
    final finalHeight = screenHeight * 0.67;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => MiningPlansBottomSheet(
        contractData: contractData,
        onFreePlanTap: onFreePlanTap,
        onOfferWallPlanTap: onOfferWallPlanTap,
        onRunningPlansTap: onRunningPlansTap,
        onPurchaseTap: onPurchaseTap,
      ),
    );
  }
}
